import os
from django.utils import timezone
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.http import StreamingHttpResponse
from django.urls import reverse
from django.conf import settings
import random
import csv
from django.template import loader, Context


class TestClass:
    pass

def index(request):
    return HttpResponse("this is parts index")


def handle_uploaded_file(file_obj, ext):
    now = timezone.now()
    filename = "%s%s%s%s%s%s%s%s%s" % (
        now.year, now.month, now.day, now.hour, now.minute, now.second,
        now.microsecond, random.randint(100000, 999999), ext)
    file_path = os.path.join(settings.USER_UPLOAD_DIR, filename)

    with open(file_path, 'wb+') as f:
        for chunk in file_obj.chunks():
            f.write(chunk)


def user_upload_file(request):
    if request.method == "POST":
        files = request.FILES
        if len(files) == 0:
            return HttpResponseRedirect(reverse("parts:upload_fail"))

        for file_key in files:
            file_obj = files[file_key]
            ext = os.path.splitext(file_obj.name)[1]
            handle_uploaded_file(file_obj, ext)

        return HttpResponseRedirect(reverse("parts:upload_success"))
    return render(request, "parts/upload_file.html")


def upload_success(request):
    return render(request, "parts/upload_success.html")


def upload_fail(request):
    return render(request, "parts/upload_fail.html")


def make_csv(request):
    response = HttpResponse(content_type="text/csv")
    response['Content-Disposition'] = 'attachment;filename="somefilename.csv"'

    writer = csv.writer(response)
    rows = [["Row {} , name=fffffsdfd, age=332, sss".format(idx), str(idx)]
            for idx in range(6305536)]
    for row in rows:
        writer.writerow(row)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
    return response


class Echo:

    def write(self, value):
        return value


def some_streaming_csv_view(request):

    rows = (["Row {} , name=fffffsdfd, age=332, sss".format(idx),
             str(idx)]
            for idx in range(1065536))

    pseudo_buffer = Echo()
    writer = csv.writer(pseudo_buffer)
    response = StreamingHttpResponse(
        (writer.writerow(row) for row in rows),
        content_type="text/csv")
    response['Content-Disposition'] = 'attachment;filename="somefilename2.csv"'
    return response


def make_csv_by_template(request):
    response = HttpResponse(content_type="text/csv")
    response['Content-Disposition'] = 'attachment;filename="csv_by_template.csv"'
    rows = (
        ("First row", 'Foo', 'Bar', 'Baz'),
        ('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote")
    )
    # rows = [["Row {} , name=fffffsdfd, age=332, sss".format(idx), str(idx)]
    #         for idx in range(10)]
    t = loader.get_template("csv_template.txt")
    d = dict(data=rows,)
    c = Context(d)
    t_response = t.render(d)
    response.write(t_response)
    return response

